//
//  MapNearListViewController.m
//  homeland
//
//  Created by ios on 14-10-13.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "MapNearListViewController.h"
#import "TPoiSearch.h"
#import "MyAnnotation.h"
#import "TMapView.h"
#import "MapNearLocationViewController.h"
#import "UIUnderlinedButton.h"
#import "MapNavigationViewController.h"

@interface MapNearListViewController ()<CLLocationManagerDelegate,TPoiSearchDelegate,SearchViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property(strong, nonatomic) TMapView *mapView;
@property(strong, nonatomic) TPoiSearch *poiSearch;
@property(strong, nonatomic) NSMutableArray *arrAnnotation;
@property(strong, nonatomic) MyAnnotation *_centerAnnotation;
@property(strong, nonatomic) CLLocationManager *locationManager;
@property(strong, nonatomic) IBOutlet UITableView *tableView;

@property(strong, nonatomic) NSString *distanceStr;
@property(strong, nonatomic) NSString *locationName;

@property(strong, nonatomic) IBOutlet UIImageView *classIamgeView;
@property(strong, nonatomic) IBOutlet UIImageView *distanceamgeView;

@property(strong, nonatomic) CLLocation *location;

@end

@implementation MapNearListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)backMethod
{
    if (self.locationManager != nil) {
        [self.locationManager stopUpdatingLocation];
        self.locationManager = nil;
    }
    self._centerAnnotation = nil;
    self.location = nil;
    self.mapView.delegate = nil;
    self.mapView = nil;
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"附近资源";
    self.mapView = [[TMapView alloc] init];
    self.navigationController.navigationBarHidden = NO;
    if (self.searchView == nil) {
        self.searchView = [SearchView initView];
        self.searchView.delegate = self;
        [self.searchView setFrame:CGRectMake(0, 0, 320, 43)];
        [self.view addSubview:self.searchView];
    }
    [self.tableView setFrame:CGRectMake(0, 88, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 88)];
    
    if (self.classStr == nil && [self.classStr length] == 0) {
        self.classStr = @"政府";
    }
    self.distanceStr = @"1000";
    self.classIamgeView.hidden = YES;
    self.distanceamgeView.hidden = YES;
    
    NSArray *array = @[@"政府",@"医疗",@"学校",@"银行",@"公园广场",@"公交车站",@"地铁"];
    for (int i = 0; i < array.count; i++) {
        UIUnderlinedButton *btn = [UIUnderlinedButton underlinedButton];
        [btn setTitleColor:[UIColor whiteColor] forState:0];
        [btn setFrame:CGRectMake(0, 20 + 32 * i, 81, 30)];
        [btn setTitle:array[i] forState:0];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [btn addTarget:self action:@selector(getClassTitle:) forControlEvents:64];
        [self.classIamgeView addSubview:btn];
    }
    array = @[@"500米",@"1000米",@"2000米",@"5000米"];
    for (int i = 0; i < array.count; i++) {
        UIUnderlinedButton *btn = [UIUnderlinedButton underlinedButton];
        [btn setTitleColor:[UIColor whiteColor] forState:0];
        [btn setFrame:CGRectMake(0, 20 + 32 * i, 81, 30)];
        [btn setTitle:array[i] forState:0];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [btn addTarget:self action:@selector(getDistanceTitle:) forControlEvents:64];
        [self.distanceamgeView addSubview:btn];
    }

    
//    [self performSelector:@selector(loacation) withObject:nil afterDelay:1.f];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loacation];
}

- (void)loacation
{

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 1000.0f;
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    }
}

#pragma mark
- (IBAction)changeClass:(id)sender
{
    self.classIamgeView.hidden = !self.classIamgeView.hidden;
    self.distanceamgeView.hidden = YES;
}

- (IBAction)changeDistance:(id)sender
{
    self.classIamgeView.hidden = YES;
    self.distanceamgeView.hidden = !self.distanceamgeView.hidden;
}

- (void)getClassTitle:(UIButton *)button
{
    self.classStr = button.titleLabel.text;
    [self searchMapNear:self.location.coordinate];
}

- (void)getDistanceTitle:(UIButton *)button
{
    self.distanceStr = [button.titleLabel.text substringToIndex:[button.titleLabel.text length] - 1];
    [self searchMapNear:self.location.coordinate];
}

#pragma mark
- (void)didSearchText:(NSString *)text;
{
    self.classStr = text;
    [self loacation];
}

#pragma mark - CLLocationManagerDelegate
// 地理位置发生改变时触
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [self.locationManager stopUpdatingLocation];

    if (locations.count > 0) {
        CLLocation *newLocation = (CLLocation *)[locations objectAtIndex:0];
        self.location = newLocation;
        [self searchMapNear:self.location.coordinate];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    
}

#pragma mark searchNearList
- (void)searchMapNear:(CLLocationCoordinate2D)mLocation
{
    self.classIamgeView.hidden = YES;
    self.distanceamgeView.hidden = YES;
    self.searchView.textField.text = @"";
    
    self.poiSearch = [[TPoiSearch alloc] init];
    self.poiSearch.delegate = self;
    
    TPoiSearchParam *param = [[TPoiSearchParam alloc] init];
    param.strkeyword = self.classStr;
    param.mapscal = 14;
    
    // 周边搜索(必须填写的参数 ）

    param.searchtype = aroundSearch;
    param.searchCenter = mLocation;  // 检索中心点
    param.searchradius = [self.distanceStr integerValue];  // 周边检索半径
    
    param.searchCounter = 30;
    //    param.searchbound = _mapView.mapBound;
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = 0.f;
    coordinate.longitude = 0.f;
    param.position = coordinate;
    self.poiSearch.param = param;
    if ([self.poiSearch StartSearch]) {
        
    }
    
}

// 开始检索
- (void)beginSearch:(TPoiSearch *)search {
}

// 检索到POI
- (void)Search:(TPoiSearch *)search POIresult:(NSArray *)PoiResult allcounter:(NSUInteger)allcounter tips:(NSArray *)arrTips {
    int iPos = 0;
    int iSize = [PoiResult count];
    [self.arrAnnotation removeAllObjects];
    self.arrAnnotation = nil;
    if (iSize) {
        TPoiRecord *record = nil;
        MyAnnotation *temp = nil;
        self.arrAnnotation = [[NSMutableArray alloc] initWithCapacity:iSize];
        for (; iPos < iSize; ++iPos) {
            // 添加标注
            record = [PoiResult objectAtIndex:iPos];
            temp = [[MyAnnotation alloc] init];
            temp.title = record.strName;
            temp.subtitle = record.strAddress;
            temp.coordinate = record.coordinate;
            temp.strtel = record.strtel;
            temp.distance = record.distance;
            [self.arrAnnotation addObject:temp];
//            [self.arrAnnotation addObject:record];

        }
        NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];
        [self.arrAnnotation sortUsingDescriptors:[NSArray arrayWithObject:sort]];
    }
    [self.tableView reloadData];

}

// 检索到统计结果
- (void)Search:(TPoiSearch *)search statics:(TSearchStatics *)statics tips:(NSArray *)arrTips {
}

-(void)Search:(TPoiSearch*)search buslines:(NSArray*)arrBuslines allcounter:(NSUInteger)allcounter tips:(NSArray*)arrTips
{
}

// 检索到区域结果
- (void)Search:(TPoiSearch *)search areas:(TSearchArea *)area tips:(NSArray *)arrTips {
}

// 检索到提示信息
- (void)Search:(TPoiSearch *)search sugest:(NSArray *)arrsugest {

}

// 检索失败
- (void)Search:(TPoiSearch *)search error:(NSError *)error {
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

// 设置检索参数
- (void)MapSearch:(id)sender setSearchParam:(TPoiSearchParam *)param {
}

// 选择POI
- (void)MapSearch:(id)sender selectPoiRecord:(TPoiRecord *)poi AtIndex:(int)iIndex {
}

// 选择行政区
- (void)MapSearch:(id)sender selectArea:(TSearchArea *)area {
    NSLog(@"area = %@",area.strName);
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.arrAnnotation.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 280, 30)];
        titleLabel.tag = 1000;
        titleLabel.numberOfLines = 0;
        titleLabel.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:titleLabel];
     
        UILabel *subTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 33, 300, 30)];
        subTitleLabel.tag = 2000;
        subTitleLabel.numberOfLines = 0;
        subTitleLabel.font = [UIFont systemFontOfSize:11];
        [cell.contentView addSubview:subTitleLabel];
        
        UILabel *distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 33, 300, 20)];
        distanceLabel.tag = 3000;
        distanceLabel.numberOfLines = 0;
        distanceLabel.textAlignment = NSTextAlignmentRight;
        distanceLabel.font = [UIFont systemFontOfSize:11];
        [cell.contentView addSubview:distanceLabel];
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(280, 5, 26, 26)];
        button.tag = indexPath.row;
        [button setImage:[UIImage imageNamed:@"mylocat"] forState:0];
        [button addTarget:self action:@selector(mapNavigationViewController:) forControlEvents:64];
        [cell.contentView addSubview:button];
        
    }
    MyAnnotation *record = [self.arrAnnotation objectAtIndex:indexPath.row];
    UILabel *titleLabel = (UILabel *)[cell.contentView viewWithTag:1000];
    titleLabel.text = record.title;
    [titleLabel setFrame:[self autoLabelFrame:record.title frame:titleLabel.frame font:[UIFont  systemFontOfSize:13]]];
    
    UILabel *subTitleLabel = (UILabel *)[cell.contentView viewWithTag:2000];
    subTitleLabel.text = record.subtitle;
    [subTitleLabel setFrame:[self autoLabelFrame:record.subtitle frame:subTitleLabel.frame font:[UIFont  systemFontOfSize:12]]];
    [cell setFrame:CGRectMake(0, 0, cell.frame.size.width, subTitleLabel.frame.size.height + subTitleLabel.frame.origin.y)];
    
    UILabel *distanceLabel = (UILabel *)[cell.contentView viewWithTag:3000];
    distanceLabel.text = [NSString stringWithFormat:@"%d米",record.distance];
     return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MapNearLocationViewController *vc = [MapNearLocationViewController new];
    vc.annotation = self.arrAnnotation[indexPath.row];
    vc.location = self.location;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark
- (CGRect )autoLabelFrame:(NSString *)text frame:(CGRect)frame font:(UIFont *)font;
{
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(CGRectGetWidth(frame),MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    frame.size.height = size.height + 5;
    
    return frame;
}

- (void)mapNavigationViewController:(UIButton *)button;
{
    MapNavigationViewController *vc = [MapNavigationViewController new];
    vc.annotation = self.arrAnnotation[button.tag];
    vc.location = self.location;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
